package kr.hkit.android_bookmgr.activity;

import java.io.File;
import java.util.Calendar;
import java.util.GregorianCalendar;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import kr.hkit.android_bookmgr.R;
import kr.hkit.android_bookmgr.DAO.BookDAO;
import kr.hkit.android_bookmgr.DTO.BookData;
import kr.hkit.android_bookmgr.util.ImageUtil;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class BookMarkEditActivity extends Activity { //책갈피 수정
	
	static final int CALL_CAMERA = 0; //카메라호출
	static final int CALL_GALLERY = 1; //갤러리호출
	private BookDAO mBookMgr;
	private LinearLayout startlinear, endlinear;
	private int pos;
	private int whichOne = -1;
	private View datepicker;
	private int mYear, mMonth, mDay, mHour, mMin, mSec;
	private EditText startdate, enddate;
	private Intent intent;
	private String mPathCamera ;
	private String mPathGallery = null;
	private int code;
	private ImageView img;
	private EditText name, author, publisher, totalpage;
	private BookData book;
	private String mRealPathGallery;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.bookmark_edit_activity);

		ActionBar mActionBar = getActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(true); 
		mActionBar.setHomeButtonEnabled(true);

		
		mBookMgr = BookDAO.getInstance(this);
		calendar();
		mPathCamera = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+mYear+"_"+(mMonth+1)+"_"+mDay+"_"+mHour+"_"+mMin+"_"+mSec+".jpg";
		
		Bundle bundle = this.getIntent().getExtras();
		book = bundle.getParcelable("BOOK");
		Log.d("BOOK1", book.getAuthor() + " bookmarkedit");
		
		name = (EditText) findViewById(R.id.bookmark_edit_name);
		author = (EditText) findViewById(R.id.bookmark_edit_author);
		publisher = (EditText) findViewById(R.id.bookmark_edit_publisher);
		totalpage = (EditText) findViewById(R.id.bookmark_edit_totalpage);
		startdate = (EditText) findViewById(R.id.bookmark_edit_startdateedit);
		startdate.setOnFocusChangeListener(mOnFocusChangeListener);
		enddate = (EditText) findViewById(R.id.bookmark_edit_enddateedit);
		enddate.setOnFocusChangeListener(mOnFocusChangeListener);
		img = (ImageView) findViewById(R.id.bookmark_edit_img);
		
		startlinear = (LinearLayout) findViewById(R.id.bookmark_edit_startdatelinear);
		endlinear = (LinearLayout) findViewById(R.id.bookmark_edit_enddatelinear);
		Spinner spin = (Spinner) findViewById(R.id.bookmark_edit_status);//상태 스피너
		
		name.setText(book.getName());
		author.setText(book.getAuthor());
		publisher.setText(book.getPublisher());
		totalpage.setText(book.getTotalpage()+"");
		startdate.setText(book.getStartdate());
		enddate.setText(book.getEnddate());
		
		//Toast.makeText(BookMarkEditActivity.this, book.getStatus() + "상태는?", Toast.LENGTH_SHORT).show();
		
		ImageUtil.imageLoader(BookMarkEditActivity.this);
		DisplayImageOptions options = ImageUtil.dispalyOptions();
		if (book.getImgtype()==0){ //직찍
			ImageLoader.getInstance().displayImage("file:///"+book.getBookimg(), img, options);
		}else if(book.getImgtype()==1){ //갤러리
			ImageLoader.getInstance().displayImage("content://media/"+book.getBookimg(), img, options);
		}else{ //검색
			ImageLoader.getInstance().displayImage(book.getBookimg(), img, options);
		}
		
		//스피너 
		ArrayAdapter<CharSequence> adspin = ArrayAdapter.createFromResource(BookMarkEditActivity.this, 
					R.array.addbook_direct_statuslist, android.R.layout.simple_spinner_dropdown_item);
		spin.setAdapter(adspin);
		spin.setSelection(book.getStatus());
			spin.setOnItemSelectedListener(new OnItemSelectedListener() {
				//스피너 - 상태부분
				@Override
				public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
					pos = position;
					if(position==2){ //읽는중 
						startlinear.setVisibility(LinearLayout.VISIBLE);
						endlinear.setVisibility(LinearLayout.GONE);
						enddate.setText("");
					}else if(position==3){ //읽기 완료
						startlinear.setVisibility(LinearLayout.VISIBLE);
						endlinear.setVisibility(LinearLayout.VISIBLE);
					}else{ //없음, 읽을예정은 필요없으니까 invisible
						startlinear.setVisibility(LinearLayout.GONE);
						endlinear.setVisibility(LinearLayout.GONE);
						startdate.setText("");
						enddate.setText("");
					}
				}//spinner

				@Override
				public void onNothingSelected(AdapterView<?> parent) {
				}
			});//spin.setOnItemSelectedListener
		
		
	}//onCreate
	
	
	 public boolean onOptionsItemSelected(android.view.MenuItem item) {
			switch (item.getItemId()) {
				case android.R.id.home:
					  Intent intent = new Intent(this, BookListActivity.class); 
					  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //액티비티 쌓이지 않기위해. 바로메인
					  startActivity(intent);
					  break;
			}
			return super.onOptionsItemSelected(item);

		}; //홈으로 이동
		
	
	private void calendar(){
		
		Calendar cal = new GregorianCalendar();
		mYear = cal.get(Calendar.YEAR);
		mMonth = cal.get(Calendar.MONTH);
		mDay = cal.get(Calendar.DAY_OF_MONTH);
		mHour = cal.get(Calendar.HOUR_OF_DAY);
		mMin = cal.get(Calendar.MINUTE);
		mSec = cal.get(Calendar.SECOND);
		
	}
	
	
	//datepicker용 
	 OnFocusChangeListener mOnFocusChangeListener = new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				datepicker = v;
				
				if(hasFocus)
					new DatePickerDialog(BookMarkEditActivity.this, mDateSetListener, mYear, mMonth, mDay).show();
			}
		};
		
		DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
				mYear = year;
				mMonth = monthOfYear;
				mDay = dayOfMonth;
				
				if(datepicker.getId()==R.id.bookmark_edit_startdateedit){
					startdate.setText(String.format("%d/%02d/%d", mYear, mMonth+1, mDay));
				}else if((datepicker.getId()==R.id.bookmark_edit_enddateedit)){
					enddate.setText(String.format("%d/%02d/%d", mYear, mMonth+1, mDay));
				}
			}
		};//DatePickerDialog
		
	public void mOnClick (View v) {
		switch(v.getId()){
		case R.id.bookmark_edit_img: //카메라혹은 갤러리 요요
			new AlertDialog.Builder(this)
			.setTitle("이미지 선택 방법을 고르시오.")
			.setItems(R.array.addbook_direct_pickimg, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
					String[] pickimg = getResources().getStringArray(R.array.addbook_direct_pickimg);
					Toast.makeText(getBaseContext(), pickimg[which]+"를 선택하셨습니다.", Toast.LENGTH_SHORT).show();
					
					whichOne = which;
					
					if(which==0){ //0은 카메라실행. //1은 갤러리
						intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mPathCamera)));
						startActivityForResult(intent, CALL_CAMERA);
					}else{
						intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
						intent.setType(MediaStore.Images.Media.CONTENT_TYPE); 
						startActivityForResult(intent, CALL_GALLERY);
					}
					
				}
			})
			.setNegativeButton("취소", null)
			.show();
			break;
		
		case R.id.bookmark_edit_edit: //update 쿼리 쓰기  수정 
			//Toast.makeText(getApplicationContext(), whichOne+"", Toast.LENGTH_SHORT).show();
			
			ContentValues updateRowValues = new ContentValues();
			updateRowValues.put("name", name.getText().toString());
			updateRowValues.put("author", author.getText().toString());
			updateRowValues.put("publisher", publisher.getText().toString());
			if(whichOne==0){
				updateRowValues.put("bookimg", mPathCamera.trim()); //직찍 경로
				updateRowValues.put("imgtype", 0); //imgtype 0이면 직찍
			}else if(whichOne==1){
				updateRowValues.put("bookimg", mPathGallery.trim()); //갤러리 경로
				updateRowValues.put("imgtype", 1); //imgtype 1이면  갤러리
			}else if(whichOne==-1){
				updateRowValues.put("bookimg", book.getBookimg());//원래사진...?
			}//사진수정에서는 그냥 검색사진은 안넘어가는걸로... 
			
			if(pos==3){//완ㄴ독
				updateRowValues.put("currentpage", totalpage.getText().toString());
			}else{ //읽을예정
				updateRowValues.put("currentpage", "");
			}
			updateRowValues.put("totalpage", totalpage.getText().toString());
			updateRowValues.put("status", pos);
			updateRowValues.put("startdate", startdate.getText().toString().trim());
			updateRowValues.put("enddate", enddate.getText().toString().trim());	
			
			String whereClause="_id=?";
			String[] whereArgs = new String[1];
			whereArgs[0] = Integer.toString(book.getId());//id는? 
			mBookMgr.updateBook(updateRowValues, whereClause, whereArgs);
			Toast.makeText(BookMarkEditActivity.this, "수정되었습니다.", Toast.LENGTH_SHORT).show();
			
			finish();
			break;
			
		case R.id.bookmark_edit_cancle:
			finish();
			break;
		}
	}//mOnClick
	
	
	//카메라 결과
		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			super.onActivityResult(requestCode, resultCode, data);
			
				code = requestCode;
				
			if(resultCode==RESULT_OK){
				switch(requestCode){
				case CALL_CAMERA: //카메라 호출 촬영결과
					
					updateImageView();
					//Toast.makeText(this, mPathCamera, Toast.LENGTH_LONG).show();
					break;
					
				case CALL_GALLERY: //갤러리 호출 결과
					
					Uri mImageUri = data.getData();
					mPathGallery= data.getData().getPath();//이거내꺼였음...
					mRealPathGallery = getPath(mImageUri);//이거하면 원 주소 나옴!!
					Log.d("path", "갤러리: "+mRealPathGallery);
					updateImageView();
					break;
					
				}//switch
			}//if
		}//onActivityResult
		

		 private String getPath(Uri uri) {  
		        String[] projection = { MediaStore.Images.Media.DATA };  
		  
		        Cursor cursor = managedQuery(uri, projection, null, null, null);  
		        int column_index = cursor  
		        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
		        cursor.moveToFirst();  
		  
		        return cursor.getString(column_index);  
		    }  
		 
		 
		 private void updateImageView() {  //이미지뷰에 뿌리기
			 
			 if(code==CALL_CAMERA){
				 
				 
				int degree = ImageUtil.GetExifOrientation(mPathCamera);
				Bitmap resizeBitmap = ImageUtil.loadBackgroundBitmap(BookMarkEditActivity.this, mPathCamera);

				if (degree != 0) {
					Bitmap rotateBitmap = ImageUtil.GetRotatedBitmap(resizeBitmap,degree);
					img.setImageBitmap(rotateBitmap);
					img.setScaleType(ImageView.ScaleType.FIT_XY);
					LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(220,300);
					img.setLayoutParams(param);
					
				} else {// 0이면 안돌려도됨
					
					img.setImageBitmap(resizeBitmap);
					img.setScaleType(ImageView.ScaleType.FIT_XY);
					LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(220,300); //계산해서넣었음ㅋㅋ
					img.setLayoutParams(param);
				}
				 
			 }else if (code==CALL_GALLERY){
				 
		        int degree = ImageUtil.GetExifOrientation(mRealPathGallery);  
		        Bitmap resizeBitmap = ImageUtil.loadBackgroundBitmap(BookMarkEditActivity.this, mRealPathGallery);  
		        
		        if(degree!=0){
		        	Bitmap rotateBitmap = ImageUtil.GetRotatedBitmap(resizeBitmap, degree);  
		        	img.setImageBitmap(rotateBitmap);  
		        	img.setScaleType(ImageView.ScaleType.FIT_XY);
					LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(220,300);
					img.setLayoutParams(param);
					
		        }else{//0이면 안돌려도됨
		        	img.setImageBitmap(resizeBitmap);
		        	img.setScaleType(ImageView.ScaleType.FIT_XY);
					LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(220,300); //계산해서넣었음ㅋㅋ
					img.setLayoutParams(param);
					
		        }//inner if~else
			 }//if~else
		    } //updateImageView() 
	
}
